<template>
  <div class="module-card">
    <!-- 卡片顶部装饰条 -->
    <div class="card-header">
      <div class="header-gradient"></div>
      <h3>个人中心</h3>
    </div>
    
    <div class="personal-info">
      <!-- 主要信息区域：四列布局 -->
      <div class="info-row">
        <div class="info-item">
          <label class="info-label">
            <i class="icon-user"></i> 姓名
          </label>
          <span v-if="!editingPersonalInfo" class="info-value">{{ userInfo.username || '无' }}</span>
          <input v-else v-model="tempUserInfo.username" type="text" class="info-input">
        </div>
        <div class="info-item">
          <label class="info-label">
            <i class="icon-id"></i> 学号
          </label>
          <span v-if="!editingPersonalInfo" class="info-value">{{ userInfo.studentId || '无' }}</span>
          <input v-else v-model="tempUserInfo.studentId" type="text" class="info-input">
        </div>
        <div class="info-item">
          <label class="info-label">
            <i class="icon-position"></i> 职务
          </label>
          <span v-if="!editingPersonalInfo" class="info-value">{{ userInfo.position || '无职位' }}</span>
          <input v-else v-model="tempUserInfo.position" type="text" class="info-input">
        </div>
        <div class="info-item">
          <label class="info-label">
            <i class="icon-calendar"></i> 入社时间
          </label>
          <span v-if="!editingPersonalInfo" class="info-value">{{ userInfo.joinTime || '无记录' }}</span>
          <input v-else v-model="tempUserInfo.joinTime" type="text" class="info-input" placeholder="如：2024-09">
        </div>
      </div>

      <!-- 次要信息区域：两列布局 -->
      <div class="info-row">
        <div class="info-item">
          <label class="info-label">
            <i class="icon-school"></i> 学院
          </label>
          <span v-if="!editingPersonalInfo" class="info-value">{{ userInfo.college || '无' }}</span>
          <input v-else v-model="tempUserInfo.college" type="text" class="info-input">
        </div>
        <div class="info-item">
          <label class="info-label">
            <i class="icon-phone"></i> 联系方式
          </label>
          <span v-if="!editingPersonalInfo" class="info-value">{{ userInfo.phone || '无' }}</span>
          <input v-else v-model="tempUserInfo.phone" type="text" class="info-input">
        </div>
      </div>

      <!-- 详细信息区域：两列布局的宽项目 -->
      <div class="info-row">
        <div class="info-item wide-item">
          <label class="info-label">
            <i class="icon-task"></i> 职责
          </label>
          <span v-if="!editingPersonalInfo" class="info-value block-value">{{ userInfo.duty || '无' }}</span>
          <textarea v-else v-model="tempUserInfo.duty" rows="3" class="info-textarea"></textarea>
        </div>
        <div class="info-item wide-item">
          <label class="info-label">
            <i class="icon-award"></i> 荣誉
          </label>
          <span v-if="!editingPersonalInfo" class="info-value block-value">{{ userInfo.honor || '无' }}</span>
          <input v-else v-model="tempUserInfo.honor" type="text" class="info-input" placeholder="可填写多项，用逗号分隔">
        </div>
      </div>
    </div>

    <div class="operation-buttons">
      <button v-if="!editingPersonalInfo" @click="startEditPersonalInfo" class="btn btn-primary">
        <i class="icon-edit"></i> 编辑信息
      </button>
      <div v-else class="edit-buttons">
        <button @click="savePersonalInfo" class="btn btn-primary">
          <i class="icon-save"></i> 保存
        </button>
        <button @click="cancelEditPersonalInfo" class="btn btn-secondary">
          <i class="icon-cancel"></i> 取消
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'

// 个人中心数据
const userInfo = ref({
  username: '',
  studentId: '',
  college: '',
  phone: '',
  honor: '',
  duty: '',
  position: '',
  joinTime: '',
  id: null,
  infoId: null
})
const tempUserInfo = ref({})
const editingPersonalInfo = ref(false)

// 获取当前用户信息
const fetchUserInfo = async () => {
  try {
    // 从登录状态获取userId
    const authData = localStorage.getItem('auth')
    if (!authData) {
      throw new Error('未登录')
    }
    
    const { user } = JSON.parse(authData)
    const userId = user.id
    
    const [userResponse, infoResponse] = await Promise.all([
      fetch(`http://localhost:8080/user/${userId}`),
      fetch(`http://localhost:8080/userInfo/user/${userId}`)
    ])
    
    const [userResult, infoResult] = await Promise.all([
      userResponse.json(),
      infoResponse.json()
    ])
    
    if (userResult.code === 200 && infoResult.code === 200) {
      userInfo.value = {
        ...userResult.data,
        ...infoResult.data,
        id: userResult.data.id,
        infoId: infoResult.data.infoId
      }
      tempUserInfo.value = { ...userInfo.value }
    }
  } catch (error) {
    console.error('获取个人信息失败:', error)
    alert('获取个人信息失败，请刷新重试')
  }
}

// 开始编辑个人信息
const startEditPersonalInfo = () => {
  tempUserInfo.value = { ...userInfo.value }
  editingPersonalInfo.value = true
}

// 取消编辑
const cancelEditPersonalInfo = () => {
  editingPersonalInfo.value = false
}

// 保存个人信息
const savePersonalInfo = async () => {
  try {
    // 准备更新数据（包含学号和姓名的更新，与原逻辑保持一致）
    const userUpdateData = {
      id: userInfo.value.id,
      username: tempUserInfo.value.username,
      studentId: tempUserInfo.value.studentId // 新增学号更新（若后端支持）
    }
    
    const infoUpdateData = {
      infoId: userInfo.value.infoId,
      college: tempUserInfo.value.college,
      phone: tempUserInfo.value.phone,
      honor: tempUserInfo.value.honor,
      duty: tempUserInfo.value.duty,
      position: tempUserInfo.value.position, // 新增职务更新
      joinTime: tempUserInfo.value.joinTime // 新增入社时间更新
    }
    
    // 并行发送更新请求
    const [userResponse, infoResponse] = await Promise.all([
      fetch('http://localhost:8080/user/update', {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(userUpdateData)
      }),
      fetch('http://localhost:8080/userInfo/update', {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(infoUpdateData)
      })
    ])
    
    const [userResult, infoResult] = await Promise.all([
      userResponse.json(),
      infoResponse.json()
    ])
    
    if (userResult.code === 200 && infoResult.code === 200) {
      userInfo.value = { ...tempUserInfo.value }
      editingPersonalInfo.value = false
      alert('信息更新成功')
    } else {
      throw new Error(infoResult.message || userResult.message || '更新失败')
    }
  } catch (error) {
    console.error('保存个人信息失败:', error)
    alert(error.message || '保存失败，请重试')
  }
}

onMounted(() => {
  fetchUserInfo()
})
</script>

<style scoped>
/* 自定义图标样式 */
[class^="icon-"]::before {
  display: inline-block;
  width: 20px;
  height: 20px;
  margin-right: 8px;
  text-align: center;
  font-weight: bold;
}

.icon-user::before { content: "👤"; }
.icon-id::before { content: "🆔"; }
.icon-position::before { content: "🎯"; }
.icon-calendar::before { content: "📅"; }
.icon-school::before { content: "🏫"; }
.icon-phone::before { content: "📞"; }
.icon-task::before { content: "📋"; }
.icon-award::before { content: "🏆"; }
.icon-edit::before { content: "✏️"; }
.icon-save::before { content: "💾"; }
.icon-cancel::before { content: "❌"; }

/* 基础卡片样式 - 现代化设计 */
.module-card {
  max-width: 1200px;
  margin: 2.5rem auto;
  padding: 0;
  background-color: #ffffff;
  border-radius: 24px;
  box-shadow: 0 12px 36px rgba(0, 0, 0, 0.08);
  font-family: 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
  overflow: hidden;
  position: relative;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(226, 232, 240, 0.5);
}

.module-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 16px 48px rgba(0, 0, 0, 0.12);
}

/* 卡片顶部设计 */
.card-header {
  position: relative;
  padding: 2.2rem 2.2rem 0;
}

.header-gradient {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 6px;
  background: linear-gradient(90deg, #6366f1 0%, #8b5cf6 100%);
  border-radius: 6px 6px 0 0;
}

/* 标题样式 */
.module-card h3 {
  margin: 1.5rem 0 1.8rem;
  padding-bottom: 1rem;
  color: #1e293b;
  font-size: 1.8rem;
  font-weight: 700;
  border-bottom: 1px solid #f1f5f9;
  position: relative;
}

.module-card h3::after {
  content: '';
  position: absolute;
  bottom: -1px;
  left: 0;
  width: 80px;
  height: 3px;
  background: linear-gradient(90deg, #6366f1 0%, #8b5cf6 100%);
  border-radius: 3px;
}

/* 信息容器 */
.personal-info {
  margin-bottom: 2rem;
  padding: 0 2.2rem;
}

/* 行布局：用于多列并排的信息项 */
.info-row {
  display: flex;
  gap: 2.5rem;
  margin-bottom: 1.8rem;
  align-items: center;
  flex-wrap: wrap;
}

/* 全屏宽度行：用于职责、荣誉等单独一行的信息项 */
.info-row.full-width {
  align-items: flex-start; /* 文本域顶部对齐 */
}

/* 基础信息项样式 */
.info-item {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
  flex: 1;
  padding: 1rem;
  border-radius: 12px;
  background-color: #f8fafc;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
  border: 1px solid transparent;
}

.info-item:hover {
  background-color: #f1f5f9;
  border-color: #e2e8f0;
  transform: translateY(-2px);
  box-shadow: 0 6px 18px rgba(0, 0, 0, 0.06);
}

.info-item::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 4px;
  height: 0;
  background: linear-gradient(180deg, #6366f1 0%, #8b5cf6 100%);
  transition: height 0.3s ease;
  border-radius: 0 0 2px 2px;
}

.info-item:hover::before {
  height: 100%;
}

/* 全屏宽度信息项（职责、荣誉） */
.info-item.full-item {
  width: 100%;
}

/* 宽项目样式 */
.info-item.wide-item {
  flex: 1;
  min-width: 400px;
}

/* 标签样式 */
.info-label {
  font-size: 0.9rem;
  font-weight: 600;
  color: #64748b;
  text-transform: capitalize;
  display: flex;
  align-items: center;
  transition: color 0.3s ease;
}

.info-item:hover .info-label {
  color: #4f46e5;
}

/* 文本显示样式 */
.info-value {
  font-size: 1rem;
  color: #1e293b;
  line-height: 1.6;
  padding: 0.5rem 0;
  font-weight: 500;
  position: relative;
  transition: color 0.3s ease;
}

.info-item:hover .info-value {
  color: #374151;
}

/* 块级文本样式 */
.block-value {
  padding: 0.8rem 1rem;
  background-color: #ffffff;
  border-radius: 8px;
  border: 1px solid #e2e8f0;
  min-height: 60px;
  transition: all 0.3s ease;
}

.info-item:hover .block-value {
  border-color: #cbd5e1;
  background-color: #f8fafc;
}

/* 输入框和文本域通用样式 */
.info-input, .info-textarea {
  padding: 0.8rem 1rem;
  border: 2px solid #e2e8f0;
  border-radius: 8px;
  font-size: 0.95rem;
  color: #1e293b;
  transition: all 0.3s ease;
  background-color: #ffffff;
  font-family: inherit;
  font-weight: 500;
  box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.03);
}

/* 输入框聚焦效果 */
.info-input:focus, .info-textarea:focus {
  outline: none;
  border-color: #6366f1;
  box-shadow: 0 0 0 4px rgba(99, 102, 241, 0.1);
  background-color: #ffffff;
  transform: translateY(-1px);
}

/* 文本域特殊样式 */
.info-textarea {
  min-height: 100px;
  resize: vertical;
  line-height: 1.6;
  padding: 0.8rem 1rem;
}

/* 按钮区域样式 */
.operation-buttons {
  display: flex;
  justify-content: flex-end;
  gap: 1.2rem;
  padding: 1.5rem 2.2rem;
  border-top: 1px solid #f1f5f9;
  background-color: #f8fafc;
}

.edit-buttons {
  display: flex;
  gap: 1.2rem;
}

/* 按钮通用样式 */
.btn {
  padding: 0.8rem 1.6rem;
  border-radius: 10px;
  font-size: 0.95rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  min-width: 110px;
  position: relative;
  overflow: hidden;
}

/* 主按钮样式 */
.btn-primary {
  background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%);
  color: #ffffff;
  box-shadow: 0 4px 12px rgba(99, 102, 241, 0.25);
}

.btn-primary::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent 0%, rgba(255, 255, 255, 0.3) 50%, transparent 100%);
  transition: left 0.6s ease;
}

.btn-primary:hover {
  background: linear-gradient(135deg, #4f46e5 0%, #7c3aed 100%);
  box-shadow: 0 6px 18px rgba(99, 102, 241, 0.35);
  transform: translateY(-2px);
}

.btn-primary:hover::before {
  left: 100%;
}

.btn-primary:active {
  transform: translateY(0);
  box-shadow: 0 4px 12px rgba(99, 102, 241, 0.25);
}

/* 次要按钮样式 */
.btn-secondary {
  background-color: #f1f5f9;
  color: #475569;
  border: 2px solid #e2e8f0;
}

.btn-secondary:hover {
  background-color: #e2e8f0;
  color: #334155;
  border-color: #cbd5e1;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.btn-secondary:active {
  transform: translateY(0);
  box-shadow: none;
}

/* 响应式适配（PC端小屏幕优化） */
@media (max-width: 768px) {
  .module-card {
    margin: 1.5rem;
  }
  
  .card-header {
    padding: 1.8rem 1.8rem 0;
  }
  
  .personal-info {
    padding: 0 1.8rem;
  }
  
  .operation-buttons {
    padding: 1.5rem 1.8rem;
  }
  
  /* 小屏幕下改为单列布局 */
  .info-row {
    flex-direction: column;
    gap: 1.2rem;
    margin-bottom: 1.2rem;
  }
  
  .info-item {
    width: 100%;
  }
  
  .edit-buttons {
    flex-direction: column;
    width: 100%;
  }
  
  .btn {
    width: 100%;
    justify-content: center;
  }
}

/* 动画效果 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.info-item {
  animation: fadeIn 0.4s ease-out forwards;
}

.info-item:nth-child(1) { animation-delay: 0.1s; }
.info-item:nth-child(2) { animation-delay: 0.2s; }
.info-item.full-item { animation-delay: 0.3s; }
</style>